package cn.haoma.base.http;

import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;

import java.io.Serializable;

import cn.haoma.base.utils.L;
import cn.haoma.base.network.ConfigConst;


public abstract class HttpHelper {

    public static final String TAG_REQUEST = "REQUEST_" + ConfigConst.LOG_TAG_HTTP;
    public static final String TAG_RESPONSE = "RESPONSE" + ConfigConst.LOG_TAG_HTTP;
    private static HttpClient httpClient;

    public static void cancelAllRequest() {
        if (null != httpClient) {
            httpClient.cancelAllRequests(true);
        }
    }

    public static AsyncHttpClient executeGet(Class clazz, String url, final HttpCallBack callBack) {
        return executeGet(clazz, url, null, callBack);
    }

    public static <T> AsyncHttpClient executeGet(final Class clazz, String url, RequestParams params, final HttpCallBack callBack) {
        final HttpClient httpClientient = getHttpClient();
        //        if (null != params) {
        //            params.setUseJsonStreamer(true);
        //        }
        TokenUtil.setToken(params);
        String str = "GET:" + url + '?' + params.toString() + "\n";
        L.i(TAG_REQUEST, str);
        L.saveToLog(str);
        httpClientient.get(url, params, getResponseHandler(clazz, callBack, httpClientient));
        return httpClientient;
    }

    private static HttpClient getHttpClient() {
        if (null == httpClient) {
            httpClient = new HttpClient();
            httpClient.setTimeout(10000);
        }
        return httpClient;
    }

    private static TextHttpResponseHandler getResponseHandler(final Class clazz, final HttpCallBack callBack, final HttpClient httpClientient) {
        return new TextHttpResponseHandler() {
            @Override
            public void onFailure(int resultCode, Header[] headers, String s, Throwable throwable) {
                L.i(TAG_RESPONSE, "RESULT_CODE:" + resultCode + "    " + s + "\n");
                if (httpClientient.isCanceled) return;
                callBack.onCallBack();
                callBack.onNetError();
            }

            @Override
            public void onSuccess(int resultCode, Header[] headers, String content) {
                String logStr = content + "\n";
                L.i(TAG_RESPONSE, logStr);
                L.saveToLog("Res:" + logStr);
                try {
                    callBack.onCallBack();
                    if (httpClientient.isCanceled) return;
                    DataWraper dataWrapter = null;
                    try {
                        dataWrapter = JSONObject.parseObject(content, DataWraper.class);
                    } catch (Exception e) {
                        L.e(e);
                    }
                    switch (dataWrapter.getStatus()) {
                        case 1:
                            if (clazz != String.class && null != dataWrapter.getBody()) {
                                dataWrapter.setBody(JSONObject.<Serializable>parseObject(dataWrapter.getBody().toString(), clazz));
                            }
                            callBack.onSucceed(dataWrapter);
                            break;
                        case 2://请求错误，读取errorMsg
                            callBack.onServerError(dataWrapter);
                            break;
                        case 3://服务器内部错误
                            callBack.onServerError(dataWrapter);
                            break;
                    }
                } catch (Exception e) {
                    L.e(e);
                }

            }
        };
    }

    public static AsyncHttpClient executePost(final Class clazz, String url, final HttpCallBack callBack) {
        return executePost(clazz, url, null, callBack);
    }

    public static AsyncHttpClient executePost(final Class clazz, final String url, RequestParams params, final HttpCallBack callBack) {
        final HttpClient httpClientient = getHttpClient();
        //        if (null != params) {
        //            params.setUseJsonStreamer(true);
        //        }
        String str = "POST:" + url + '?' + params.toString() + "\n";
        L.i(TAG_REQUEST, str);
        L.saveToLog(str);
        httpClientient.post(url, params, getResponseHandler(clazz, callBack, httpClientient));
        return httpClientient;
    }

    public static AsyncHttpClient executePut(Class clazz, String url, final HttpCallBack callBack) {
        return executePut(clazz, url, null, callBack);
    }

    public static AsyncHttpClient executePut(final Class clazz, String url, RequestParams params, final HttpCallBack callBack) {
        final HttpClient httpClientient = getHttpClient();
        //        if (null != params) {
        //            params.setUseJsonStreamer(true);
        //        }
        httpClientient.put(url, params, getResponseHandler(clazz, callBack, httpClientient));
        return httpClientient;
    }

    public static class HttpClient extends AsyncHttpClient {
        boolean isCanceled;

        public void cancel() {
            isCanceled = true;
            cancelAllRequests(true);
        }

    }

}

